<?php
/**
 * Created by PhpStorm.
 * User: chengchaogui
 * Date: 2017/8/13
 * Time: 16:16
 */

namespace App\Repository\Service;


use App\Framework\Config\SystemConstant;
use App\Framework\Enum\ExchangeRecordStatusEnum;
use App\Framework\Helper\TextHelper;
use App\Framework\Helper\TimeHelper;
use App\Framework\Helper\UploadHelper;
use App\Framework\Model\Message;
use App\Models\Game\Activity;
use App\Models\Game\Broadcast;
use App\Models\Game\CoinStati;
use App\Models\Game\ExechangeRecord;
use App\Models\Game\Product;
use App\Models\Game\SinglePage;
use App\Models\Game\UserFeedback;
use App\Repository\Contract\IRzjhpGame;
use Log;
use Excel;
use DB;

/**
 * 游戏业务服务类
 * Class RzjhpGameService
 * @package App\Repository\Service
 */
class RzjhpGameService implements IRzjhpGame
{
    use BaseApiService;

    //region 活动

    /**
     * 根据ID获取活动
     * @param $id
     * @return mixed
     */
    public function getActivityById($id)
    {
        $activity = Activity::where('activity_id', $id)->first();
        return $activity;
    }

    /**
     * 获取活动列表
     * @param $form
     * @return mixed
     */
    public function getActivityList($form)
    {
        $activities = Activity::where(function ($query) use ($form) {
            if (!empty($form->id)) {
                $query->where('activity_id', $form->id);
            }
            if (!empty($form->name)) {
                $query->where('name', 'like', '%' . $form->name . '%');
            }
        })->orderBy('sort', 'asc')->paginate(SystemConstant::ADMIN_TABLE_ROWS);

        return $activities;
    }

    /**
     * 获取序号最大的活动
     * @return mixed
     */
    public function getActivityByMaxSort()
    {
        $activity = Activity::orderBy('sort', 'desc')->first();
        return $activity;
    }


    /**
     * 新增活动
     * @param $form
     * @return mixed
     */
    public function addActivity($form)
    {
        $activity = new Activity();
        $activity->name = $form->name;
        $activity->status = $form->status;
        $activity->content = $form->content;
        if (!empty($form->intro)) {
            $activity->intro = $form->intro;
        }

        $file = $form->file('photo');
        if ($file != null) {
            $upResult = UploadHelper::uploadImageToOss($file);
            if ($upResult->fail) {
                return $upResult;
            }

            $activity->image_path = $upResult->value;
        }

        if (!empty($form->targetLink)) {
            $activity->target_link = $form->targetLink;
        }
        if (!empty($form->rule)) {
            $activity->rule = $form->rule;
        }
        if (!empty($form->publishDate) && !empty($form->publishTime)) {
            $publishDate = TimeHelper::jointDateTime($form->publishDate, $form->publishTime);
            $activity->publish_date = $publishDate;
        }
        if (!empty($form->finishDate) && !empty($form->finishTime)) {
            $publishDate = TimeHelper::jointDateTime($form->finishDate, $form->finishTime);
            $activity->finish_date = $publishDate;
        }

        $maxActivity = $this->getActivityByMaxSort();
        $actSort = 0;
        if (!empty($maxActivity)) {
            $actSort = $maxActivity->sort + 1;
        }

        $activity->sort = $actSort;
        $activity->save();
        return Message::setTrue('发布成功');
    }

    /**
     * 修改活动
     * @param $form
     * @return mixed
     */
    public function updateActivity($form)
    {
        $activity = Activity::find($form->id);
        if (empty($activity)) {
            return Message::setFalse("修改的活动不存在");
        }

        $activity->name = $form->name;
        $activity->status = $form->status;
        $activity->content = $form->content;
        if (!empty($form->intro)) {
            $activity->intro = $form->intro;
        }

        $file = $form->file('photo');
        if ($file != null) {
            $upResult = UploadHelper::uploadImageToOss($file);
            if ($upResult->fail) {
                return $upResult;
            }

            $activity->image_path = $upResult->value;
        }

        if (!empty($form->targetLink)) {
            $activity->target_link = $form->targetLink;
        }
        if (!empty($form->rule)) {
            $activity->rule = $form->rule;
        }
        if (!empty($form->publishDate) && !empty($form->publishTime)) {
            $publishDate = TimeHelper::jointDateTime($form->publishDate, $form->publishTime);
            $activity->publish_date = $publishDate;
        }
        if (!empty($form->finishDate) && !empty($form->finishTime)) {
            $publishDate = TimeHelper::jointDateTime($form->finishDate, $form->finishTime);
            $activity->finish_date = $publishDate;
        }

        $activity->save();
        return Message::setTrue('修改成功');
    }

    /**
     * 将活动排序序号向上移动
     * @param $id
     * @return mixed
     */
    public function setActivitySortUp($id)
    {
        $activity = Activity::find($id);
        if (empty($activity)) {
            return Message::setFalse('活动不存在');
        }

        $upActivity = Activity::orderBy('sort', 'desc')->where('sort', '<', $activity->sort)->first();
        if (empty($upActivity)) {
            return Message::setFalse('该活动已处于第一位，不能再移动了');
        }

        $upSort = $upActivity->sort;
        $downSort = $activity->sort;
        $activity->sort = $upSort;
        $upActivity->sort = $downSort;

        $activity->save();
        $upActivity->save();
        return Message::setTrue('设置成功');
    }

    /**
     * 将活动排序序号向下移动
     * @param $id
     * @return mixed
     */
    public function setActivitySortDown($id)
    {
        $activity = Activity::find($id);
        if (empty($activity)) {
            return Message::setFalse('活动不存在');
        }

        $upActivity = Activity::orderBy('sort', 'asc')->where('sort', '>', $activity->sort)->first();
        if (empty($upActivity)) {
            return Message::setFalse('该活动已处于最后一位，不能再移动了');
        }

        $upSort = $upActivity->sort;
        $downSort = $activity->sort;
        $activity->sort = $upSort;
        $upActivity->sort = $downSort;

        $activity->save();
        $upActivity->save();
        return Message::setTrue('设置成功');
    }


    /**
     * 删除活动
     * @param $id
     * @return mixed
     */
    public function deleteActivity($id)
    {
        Activity::where('activity_id', $id)->delete();
        return Message::setTrue('删除成功');
    }

    /**
     * 批量删除活动
     * @param $ids
     * @return mixed
     */
    public function batchDeleteActivity($ids)
    {
        Activity::destroy($ids);
        return Message::setTrue('删除成功');
    }

    //endregion

    //region  商品

    /**
     * 根据ID获取商品
     * @param $id
     * @return mixed
     */
    public function getProductById($id)
    {
        $product = Product::find($id);
        return $product;
    }

    /**
     * 查询商品
     * @param $form
     * @return mixed
     */
    public function getProductList($form)
    {
        $products = Product::where(function ($query) use ($form) {
            if (!empty($form->id)) {
                $query->where('product_id', $form->id);
            }
            if (!empty($form->name)) {
                $query->where('name', 'like', '%' . $form->name . '%');
            }
        })->orderBy('sort', 'asc')->paginate(SystemConstant::ADMIN_TABLE_ROWS);

        return $products;
    }

    /**
     * 添加商品
     * @param $form
     * @return mixed
     */
    public function addProduct($form)
    {
        $file = $form->file('photo');
        $upResult = UploadHelper::uploadImageToOss($file);
        if ($upResult->fail) {
            return $upResult;
        }

        $product = new Product();
        $product->name = $form->name;
        $product->type = $form->type;
        $product->status = $form->status;
        $product->ticket_num = $form->ticketNum;
        $product->stock_num = $form->stockNum;
        $product->image_path = $upResult->value;
        $product->intro = $form->intro;
        $product->create_date = TimeHelper::getNow();

        $setSort = 0;
        $sortProduct = Product::orderBy('sort', 'desc')->first();
        if (!empty($sortProduct)) {
            $setSort = $sortProduct->sort + 1;
        }

        $product->sort = $setSort;
        $product->save();
        return Message::setTrue('添加成功');
    }

    /**
     * 修改商品
     * @param $form
     * @return mixed
     */
    public function updateProduct($form)
    {
        $product = Product::find($form->id);
        $product->type = $form->type;
        $product->status = $form->status;

        if (empty($product)) {
            return Message::setFalse('商品不存在');
        }

        if (!empty($form->name)) {
            $product->name = $form->name;
        }

        $file = $form->file('photo');
        if (!empty($file)) {
            $upResult = UploadHelper::uploadImageToOss($file);
            if ($upResult->fail) {
                return $upResult;
            }

            $product->image_path = $upResult->value;
        }

        if (!empty($form->ticketNum)) {
            $product->ticket_num = $form->ticketNum;
        }

        if (!empty($form->intro)) {
            $product->intro = $form->intro;
        }

        if (!empty($form->stockNum)) {
            $product->stock_num = $form->stockNum;
        }

        $product->save();
        return Message::setTrue('修改成功');
    }

    /**
     * 将商品排序序号向上移动
     * @param $id
     * @return mixed
     */
    public function setProductSortUp($id)
    {
        $prodcut = Product::find($id);
        if (empty($prodcut)) {
            return Message::setFalse('商品不存在');
        }

        $upProduct = Product::orderBy('sort', 'desc')->where('sort', '<', $prodcut->sort)->first();
        if (empty($upProduct)) {
            return Message::setFalse('该商品已处于第一位，不能再移动了');
        }

        $upSort = $upProduct->sort;
        $downSort = $prodcut->sort;
        $prodcut->sort = $upSort;
        $upProduct->sort = $downSort;

        $prodcut->save();
        $upProduct->save();
        return Message::setTrue('设置成功');
    }

    /**
     * 将商品排序序号向下移动
     * @param $id
     * @return mixed
     */
    public function setProductSortDown($id)
    {
        $prodcut = Product::find($id);
        if (empty($prodcut)) {
            return Message::setFalse('商品不存在');
        }

        $upProduct = Product::orderBy('sort', 'asc')->where('sort', '>', $prodcut->sort)->first();
        if (empty($upProduct)) {
            return Message::setFalse('该商品已处于最后一位，不能再移动了');
        }

        $upSort = $upProduct->sort;
        $downSort = $prodcut->sort;
        $prodcut->sort = $upSort;
        $upProduct->sort = $downSort;

        $prodcut->save();
        $upProduct->save();
        return Message::setTrue('设置成功');
    }

    /**
     * 删除商品
     * @param $id
     * @return mixed
     */
    public function deleteProduct($id)
    {
        Product::where('product_id', $id)->delete();
        return Message::setTrue('删除成功');
    }

    /**
     * 批量删除商品
     * @param $ids
     * @return mixed
     */
    public function batchDeleteProduct($ids)
    {
        Product::destroy($ids);
        return Message::setTrue('删除成功');
    }

    //endregion

    //region 兑换记录

    /**
     * 获取兑换记录
     * @param $id
     * @return mixed
     */
    public function getExchangeRecord($id)
    {
        $record = ExechangeRecord::find($id);
        return $record;
    }

    /**
     * 获取兑换记录列表
     * @param $form
     * @return mixed
     */
    public function getExchangeRecordList($form)
    {
        $query = ExechangeRecord::where(function ($query) use ($form) {
            if (!empty($form->id)) {
                $query->where('exchange_record_id', $form->id);
            }
            if (!empty($form->productName)) {
                $query->where('prodcut_name', 'like', '%' . $form->productName . '%');
            }
            if (!empty($form->user_id)) {
                $query->where('user_id', $form->userID);
            }
            if (!empty($form->status)) {
                $query->where('status', $form->status);
            }
            if (!empty($form->startDate)) {
                $query->where('create_date', '>=', TimeHelper::getStartTime($form->startDate));
            }
            if (!empty($form->endDate)) {
                $query->where('create_date', '<=', TimeHelper::getEndTime($form->endDate));
            }
        });

        //导出excel报表
        if ($form->export) {
            $this->exportExchangeRecord($query);
        }

        $records = $query->orderBy('exchange_record_id', 'desc')->paginate(SystemConstant::ADMIN_TABLE_ROWS);
        return $records;
    }

    /**
     * 修改兑换记录
     * @param $form
     * @return mixed
     */
    public function updateExchangeRecord($form)
    {
        $record = ExechangeRecord::find($form->id);
        if (empty($record)) {
            return Message::setFalse('记录不存在');
        }

        $record->status = $form->status;
        $record->status_desc = ExchangeRecordStatusEnum::getName($form->status);
        $record->deal_date = TimeHelper::getNow();
        if (!empty($form->comment)) {
            $record->comment = $form->comment;
        }

        $record->save();
        return Message::setTrue('修改成功');
    }

    /**
     * 批量设置兑换记录状态
     * @param $ids
     * @param $status
     * @return mixed
     */
    public function setExchangeRecordStatus($ids, $status)
    {
        foreach ($ids as $id) {
            $record = ExechangeRecord::find($id);
            $record->status = $status;
            $record->deal_date = TimeHelper::getNow();
            $record->save();
        }

        return Message::setTrue('修改成功');
    }

    /**
     * 根据查询条件导出excel报表
     * @param $query
     */
    private function exportExchangeRecord($query)
    {
        //查询订单数据，按时间倒序
        $records = $query->orderBy('create_date', 'desc')->get();
        $cellData = [
            ['订单ID', '商品名称', '数量', '用户ID', '手机号', '订单时间', '状态']
        ];

        foreach ($records as $item) {
            $arr = [$item->exchange_record_id, $item->product_name, $item->quantity, $item->user_id, $item->telephone, $item->create_date, ExchangeRecordStatusEnum::getName($item->status)];
            array_push($cellData, $arr);
        }

        Excel::create('兑换记录', function ($excel) use ($cellData) {
            $excel->sheet('兑换记录', function ($sheet) use ($cellData) {
                $sheet->setWidth(array(
                    'A' => 20,
                    'B' => 30,
                    'C' => 10,
                    'D' => 10,
                    'E' => 20,
                    'F' => 30,
                    'G' => 10,
                ));
                $sheet->rows($cellData);
            })->export('xls');
        });
    }

    //endregion

    /**
     * 获取单页列表
     * @return mixed
     */
    public function getSinlePageList()
    {
        $pageList = SinglePage::all();
        return $pageList;
    }

    /**
     * 修改单页
     * @param $form
     * @return mixed
     */
    public function updateSinglePage($form)
    {
        $page = SinglePage::find($form->id);
        if (empty($page)) {
            return Message::setFalse('单页不存在');
        }

        $page->content = $form->content;
        $page->save();
        return Message::setTrue('修改成功');
    }

    /**
     * 根据ID查询用户反馈
     * @param $id
     * @return mixed
     */
    public function getUserFeedback($id)
    {
        $feed = UserFeedback::find($id);
        return $feed;
    }

    /**
     * 查询用户反馈列表
     * @param $form
     * @return mixed
     */
    public function getUserFeedbackList($form)
    {
        $list = UserFeedback::where(function ($query) use ($form) {
            if (!empty($form->userID)) {
                $query->where('user_id', $form->userID);
            }
            if (!empty($form->nickname)) {
                $query->where('nickname', 'like', '%' . $form->nickname . '%');
            }
        })->orderBy('user_feedback_id', 'desc')->paginate(SystemConstant::ADMIN_TABLE_ROWS);

        return $list;
    }

    /**
     * 删除用户反馈
     * @param $id
     * @return mixed
     */
    public function deleteUserFeedback($id)
    {
        UserFeedback::where('user_feedback_id', $id)->delete();
        return Message::setTrue('删除成功');
    }

    /**
     * 获取广播列表
     * @param $form
     * @return mixed
     */
    public function getBroadcastList($form)
    {
        $list = Broadcast::where(function ($query) use ($form) {
            if (!empty($form->userID)) {
                $query->where('user_id', $form->userID);
            }
            if ($form->type != null) {
                $query->where('type', $form->type);
            }
            if (!empty($form->startDate)) {
                $query->where('send_date', '<=', $form->startDate);
            }
            if (!empty($form->endDate)) {
                $query->where('send_date', '>=', $form->endDate);
            }
        })->orderBy('broadcast_id', 'desc')->paginate(SystemConstant::ADMIN_TABLE_ROWS);

        return $list;
    }

    /**
     * 发送广播
     * @param $form
     * @return mixed
     */
    public function addBroadcast($form)
    {
        if ($form->type == 0) {
            if (empty($form->userID)) {
                return Message::setFalse('请填写接收消息的玩家ID');
            }
        }

        //将消息推送到游戏服务器
        $apiArr = array(
            'gameId' => '9999',
            'mtype' => $form->type,
            'msg' => $form->content
        );

        if ($form->type == 0) {
            $apiArr['toUid'] = $form->userID;
        }

        $sign = $this->generateMd5Sign($apiArr);
        $apiArr['sign'] = $sign;
        $apiArr['msg'] = urlencode($form->content);//将内容做url编码
        $queryString = $this->getApiQueryString($apiArr);
        $url = 'http://111.203.187.181:8550/_gdss/msg/sendmsg?' . $queryString;
        Log::info('sss--->' . $url);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($curl);
        curl_close($curl);
        Log::info('发送消息结果：' . $response);
        $result = json_decode($response);

        if ($result->result->code != '0') {
            return Message::setFalse('推送消息失败-->' . $result->result->info);
        }

        $cast = new Broadcast();
        $cast->type = $form->type;
        $cast->game_id = 9999;
        $cast->content = $form->content;
        $cast->send_date = TimeHelper::getNow();
        if (!empty($form->userID)) {
            $cast->user_id = $form->userID;
        }

        //保存至数据库
        $cast->save();

        return Message::setTrue('发送成功');
    }

    /**
     * 删除广播
     * @param $id
     * @return mixed
     */
    public function deleteBroadcast($id)
    {
        Broadcast::where('broadcast_id', $id)->delete();
        return Message::setTrue('删除成功');
    }


    /**
     * 查询金币汇总
     * @param $form
     * @return mixed
     */
    public function getCoinStatiList($form)
    {
        $list = CoinStati::where(function ($query) use ($form) {
            if (!empty($form->startDate)) {
                $query->where('stati_date', '<=', $form->startDate);
            }
            if (!empty($form->endDate)) {
                $query->where('stati_date', '>=', $form->endDate);
            }
        })->orderBy('stati_date', 'desc')->paginate(SystemConstant::ADMIN_TABLE_ROWS);

        $coin_total = DB::select('select sum(recharge_coin) from coin_stati');
        $commision_total = DB::select('select sum(commision_coin) from coin_stati');

        $list['coin_total'] = $coin_total;
        $list['commision_total'] = $commision_total;
        return $list;
    }
}